{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import statsmodels.api as sm\n",
    "import matplotlib. pyplot as plt\n",
    "from statsmodels.regression.rolling import RollingOLS\n",
    "from pandas.core.frame import DataFrame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>MarkettypeID</th>\n",
       "      <th>TradingDate</th>\n",
       "      <th>RiskPremium1</th>\n",
       "      <th>RiskPremium2</th>\n",
       "      <th>SMB1</th>\n",
       "      <th>SMB2</th>\n",
       "      <th>HML1</th>\n",
       "      <th>HML2</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>P9706</td>\n",
       "      <td>1990-12-19</td>\n",
       "      <td>2.473374</td>\n",
       "      <td>2.309671</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>P9710</td>\n",
       "      <td>1990-12-19</td>\n",
       "      <td>2.473374</td>\n",
       "      <td>2.309671</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>P9709</td>\n",
       "      <td>1990-12-19</td>\n",
       "      <td>2.473374</td>\n",
       "      <td>2.309671</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>P9712</td>\n",
       "      <td>1990-12-19</td>\n",
       "      <td>2.473374</td>\n",
       "      <td>2.309671</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>P9713</td>\n",
       "      <td>1990-12-19</td>\n",
       "      <td>2.473374</td>\n",
       "      <td>2.309671</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  MarkettypeID TradingDate  RiskPremium1  RiskPremium2  SMB1  SMB2  HML1  HML2\n",
       "0        P9706  1990-12-19      2.473374      2.309671   NaN   NaN   NaN   NaN\n",
       "1        P9710  1990-12-19      2.473374      2.309671   NaN   NaN   NaN   NaN\n",
       "2        P9709  1990-12-19      2.473374      2.309671   NaN   NaN   NaN   NaN\n",
       "3        P9712  1990-12-19      2.473374      2.309671   NaN   NaN   NaN   NaN\n",
       "4        P9713  1990-12-19      2.473374      2.309671   NaN   NaN   NaN   NaN"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df=pd.read_csv('STK_MKT_THRFACDAY.csv',encoding='utf_8_sig')\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\dell\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py:2: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  \n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>MarkettypeID</th>\n",
       "      <th>RiskPremium1</th>\n",
       "      <th>RiskPremium2</th>\n",
       "      <th>SMB1</th>\n",
       "      <th>SMB2</th>\n",
       "      <th>HML1</th>\n",
       "      <th>HML2</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>date</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2021-01-04</th>\n",
       "      <td>P9706</td>\n",
       "      <td>0.010357</td>\n",
       "      <td>0.010930</td>\n",
       "      <td>0.004638</td>\n",
       "      <td>0.004161</td>\n",
       "      <td>-0.010758</td>\n",
       "      <td>-0.011928</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-01-05</th>\n",
       "      <td>P9706</td>\n",
       "      <td>0.010340</td>\n",
       "      <td>0.010769</td>\n",
       "      <td>-0.012563</td>\n",
       "      <td>-0.011595</td>\n",
       "      <td>-0.016017</td>\n",
       "      <td>-0.014040</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-01-06</th>\n",
       "      <td>P9706</td>\n",
       "      <td>0.004966</td>\n",
       "      <td>0.004517</td>\n",
       "      <td>-0.018080</td>\n",
       "      <td>-0.017969</td>\n",
       "      <td>0.003920</td>\n",
       "      <td>0.003710</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-01-07</th>\n",
       "      <td>P9706</td>\n",
       "      <td>0.007401</td>\n",
       "      <td>0.006454</td>\n",
       "      <td>-0.033309</td>\n",
       "      <td>-0.032130</td>\n",
       "      <td>-0.004250</td>\n",
       "      <td>-0.004629</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-01-08</th>\n",
       "      <td>P9706</td>\n",
       "      <td>-0.002017</td>\n",
       "      <td>-0.001919</td>\n",
       "      <td>-0.005396</td>\n",
       "      <td>-0.004850</td>\n",
       "      <td>0.008191</td>\n",
       "      <td>0.008967</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           MarkettypeID  RiskPremium1  RiskPremium2      SMB1      SMB2  \\\n",
       "date                                                                      \n",
       "2021-01-04        P9706      0.010357      0.010930  0.004638  0.004161   \n",
       "2021-01-05        P9706      0.010340      0.010769 -0.012563 -0.011595   \n",
       "2021-01-06        P9706      0.004966      0.004517 -0.018080 -0.017969   \n",
       "2021-01-07        P9706      0.007401      0.006454 -0.033309 -0.032130   \n",
       "2021-01-08        P9706     -0.002017     -0.001919 -0.005396 -0.004850   \n",
       "\n",
       "                HML1      HML2  \n",
       "date                            \n",
       "2021-01-04 -0.010758 -0.011928  \n",
       "2021-01-05 -0.016017 -0.014040  \n",
       "2021-01-06  0.003920  0.003710  \n",
       "2021-01-07 -0.004250 -0.004629  \n",
       "2021-01-08  0.008191  0.008967  "
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df2=df[df.MarkettypeID=='P9706']\n",
    "df2['date']= pd.to_datetime(df2['TradingDate'],format='%Y-%m-%d')\n",
    "df2 = df2.reset_index().set_index('date')\n",
    "df2 = df2.drop(['index','TradingDate'],axis=1)\n",
    "df2=df2.dropna()\n",
    "df3=df2.loc['2021-01-01':'2021-12-01']\n",
    "df3.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "stocks = pd.read_csv('test.csv',encoding=\"utf_8\")\n",
    "stocks['date'] = pd.to_datetime(stocks['date'])\n",
    "stocks = stocks.reset_index().set_index('date')\n",
    "stocks = stocks.drop(['index'],axis=1)\n",
    "returns = np.log(stocks/stocks.shift(1))\n",
    "returns = returns.dropna()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>MarkettypeID</th>\n",
       "      <th>RiskPremium1</th>\n",
       "      <th>RiskPremium2</th>\n",
       "      <th>SMB1</th>\n",
       "      <th>SMB2</th>\n",
       "      <th>HML1</th>\n",
       "      <th>HML2</th>\n",
       "      <th>中国重汽</th>\n",
       "      <th>道恩股份</th>\n",
       "      <th>白云机场</th>\n",
       "      <th>东风汽车</th>\n",
       "      <th>中石化</th>\n",
       "      <th>中海油</th>\n",
       "      <th>中石油</th>\n",
       "      <th>上汽</th>\n",
       "      <th>比亚迪</th>\n",
       "      <th>on_b</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>date</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2021-01-05</th>\n",
       "      <td>P9706</td>\n",
       "      <td>0.010340</td>\n",
       "      <td>0.010769</td>\n",
       "      <td>-0.012563</td>\n",
       "      <td>-0.011595</td>\n",
       "      <td>-0.016017</td>\n",
       "      <td>-0.014040</td>\n",
       "      <td>-0.025414</td>\n",
       "      <td>0.061614</td>\n",
       "      <td>-0.000391</td>\n",
       "      <td>-0.016517</td>\n",
       "      <td>-0.037573</td>\n",
       "      <td>-0.002484</td>\n",
       "      <td>-0.036320</td>\n",
       "      <td>-0.041133</td>\n",
       "      <td>-0.002389</td>\n",
       "      <td>-0.209350</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-01-06</th>\n",
       "      <td>P9706</td>\n",
       "      <td>0.004966</td>\n",
       "      <td>0.004517</td>\n",
       "      <td>-0.018080</td>\n",
       "      <td>-0.017969</td>\n",
       "      <td>0.003920</td>\n",
       "      <td>0.003710</td>\n",
       "      <td>0.044676</td>\n",
       "      <td>-0.016507</td>\n",
       "      <td>0.048790</td>\n",
       "      <td>-0.019745</td>\n",
       "      <td>-0.046091</td>\n",
       "      <td>0.022141</td>\n",
       "      <td>0.011384</td>\n",
       "      <td>0.077767</td>\n",
       "      <td>0.016608</td>\n",
       "      <td>-0.179586</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-01-07</th>\n",
       "      <td>P9706</td>\n",
       "      <td>0.007401</td>\n",
       "      <td>0.006454</td>\n",
       "      <td>-0.033309</td>\n",
       "      <td>-0.032130</td>\n",
       "      <td>-0.004250</td>\n",
       "      <td>-0.004629</td>\n",
       "      <td>0.043059</td>\n",
       "      <td>0.039612</td>\n",
       "      <td>-0.044892</td>\n",
       "      <td>-0.053862</td>\n",
       "      <td>-0.005914</td>\n",
       "      <td>0.002430</td>\n",
       "      <td>0.011256</td>\n",
       "      <td>0.038806</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.410915</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-01-08</th>\n",
       "      <td>P9706</td>\n",
       "      <td>-0.002017</td>\n",
       "      <td>-0.001919</td>\n",
       "      <td>-0.005396</td>\n",
       "      <td>-0.004850</td>\n",
       "      <td>0.008191</td>\n",
       "      <td>0.008967</td>\n",
       "      <td>-0.005023</td>\n",
       "      <td>0.010916</td>\n",
       "      <td>0.014294</td>\n",
       "      <td>0.026914</td>\n",
       "      <td>-0.027663</td>\n",
       "      <td>0.016848</td>\n",
       "      <td>0.095193</td>\n",
       "      <td>0.018513</td>\n",
       "      <td>0.009368</td>\n",
       "      <td>0.083382</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-01-11</th>\n",
       "      <td>P9706</td>\n",
       "      <td>-0.011561</td>\n",
       "      <td>-0.011943</td>\n",
       "      <td>-0.015109</td>\n",
       "      <td>-0.013678</td>\n",
       "      <td>0.000027</td>\n",
       "      <td>0.001391</td>\n",
       "      <td>0.028327</td>\n",
       "      <td>0.031795</td>\n",
       "      <td>0.051581</td>\n",
       "      <td>-0.023025</td>\n",
       "      <td>-0.030962</td>\n",
       "      <td>-0.031518</td>\n",
       "      <td>0.033862</td>\n",
       "      <td>-0.015058</td>\n",
       "      <td>-0.016452</td>\n",
       "      <td>0.285179</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           MarkettypeID  RiskPremium1  RiskPremium2      SMB1      SMB2  \\\n",
       "date                                                                      \n",
       "2021-01-05        P9706      0.010340      0.010769 -0.012563 -0.011595   \n",
       "2021-01-06        P9706      0.004966      0.004517 -0.018080 -0.017969   \n",
       "2021-01-07        P9706      0.007401      0.006454 -0.033309 -0.032130   \n",
       "2021-01-08        P9706     -0.002017     -0.001919 -0.005396 -0.004850   \n",
       "2021-01-11        P9706     -0.011561     -0.011943 -0.015109 -0.013678   \n",
       "\n",
       "                HML1      HML2      中国重汽      道恩股份      白云机场      东风汽车  \\\n",
       "date                                                                     \n",
       "2021-01-05 -0.016017 -0.014040 -0.025414  0.061614 -0.000391 -0.016517   \n",
       "2021-01-06  0.003920  0.003710  0.044676 -0.016507  0.048790 -0.019745   \n",
       "2021-01-07 -0.004250 -0.004629  0.043059  0.039612 -0.044892 -0.053862   \n",
       "2021-01-08  0.008191  0.008967 -0.005023  0.010916  0.014294  0.026914   \n",
       "2021-01-11  0.000027  0.001391  0.028327  0.031795  0.051581 -0.023025   \n",
       "\n",
       "                 中石化       中海油       中石油        上汽       比亚迪      on_b  \n",
       "date                                                                    \n",
       "2021-01-05 -0.037573 -0.002484 -0.036320 -0.041133 -0.002389 -0.209350  \n",
       "2021-01-06 -0.046091  0.022141  0.011384  0.077767  0.016608 -0.179586  \n",
       "2021-01-07 -0.005914  0.002430  0.011256  0.038806  0.000000  0.410915  \n",
       "2021-01-08 -0.027663  0.016848  0.095193  0.018513  0.009368  0.083382  \n",
       "2021-01-11 -0.030962 -0.031518  0.033862 -0.015058 -0.016452  0.285179  "
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result = pd.concat([df3,returns],axis=1,join='inner')\n",
    "result.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(220, 17)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table class=\"simpletable\">\n",
       "<caption>OLS Regression Results</caption>\n",
       "<tr>\n",
       "  <th>Dep. Variable:</th>          <td>道恩股份</td>       <th>  R-squared:         </th> <td>   0.423</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Model:</th>                   <td>OLS</td>       <th>  Adj. R-squared:    </th> <td>   0.415</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Method:</th>             <td>Least Squares</td>  <th>  F-statistic:       </th> <td>   52.77</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Date:</th>             <td>Fri, 01 Apr 2022</td> <th>  Prob (F-statistic):</th> <td>1.25e-25</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Time:</th>                 <td>10:17:03</td>     <th>  Log-Likelihood:    </th> <td>  479.10</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>No. Observations:</th>      <td>   220</td>      <th>  AIC:               </th> <td>  -950.2</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Df Residuals:</th>          <td>   216</td>      <th>  BIC:               </th> <td>  -936.6</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Df Model:</th>              <td>     3</td>      <th>                     </th>     <td> </td>   \n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Covariance Type:</th>      <td>nonrobust</td>    <th>                     </th>     <td> </td>   \n",
       "</tr>\n",
       "</table>\n",
       "<table class=\"simpletable\">\n",
       "<tr>\n",
       "        <td></td>          <th>coef</th>     <th>std err</th>      <th>t</th>      <th>P>|t|</th>  <th>[0.025</th>    <th>0.975]</th>  \n",
       "</tr>\n",
       "<tr>\n",
       "  <th>const</th>        <td>    0.0014</td> <td>    0.002</td> <td>    0.744</td> <td> 0.458</td> <td>   -0.002</td> <td>    0.005</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>RiskPremium1</th> <td>    1.6093</td> <td>    0.217</td> <td>    7.400</td> <td> 0.000</td> <td>    1.181</td> <td>    2.038</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>SMB1</th>         <td>    0.0712</td> <td>    0.228</td> <td>    0.312</td> <td> 0.755</td> <td>   -0.378</td> <td>    0.521</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>HML1</th>         <td>   -1.8387</td> <td>    0.258</td> <td>   -7.134</td> <td> 0.000</td> <td>   -2.347</td> <td>   -1.331</td>\n",
       "</tr>\n",
       "</table>\n",
       "<table class=\"simpletable\">\n",
       "<tr>\n",
       "  <th>Omnibus:</th>       <td> 9.000</td> <th>  Durbin-Watson:     </th> <td>   2.101</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Prob(Omnibus):</th> <td> 0.011</td> <th>  Jarque-Bera (JB):  </th> <td>   8.921</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Skew:</th>          <td> 0.454</td> <th>  Prob(JB):          </th> <td>  0.0116</td>\n",
       "</tr>\n",
       "<tr>\n",
       "  <th>Kurtosis:</th>      <td> 3.385</td> <th>  Cond. No.          </th> <td>    150.</td>\n",
       "</tr>\n",
       "</table><br/><br/>Warnings:<br/>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified."
      ],
      "text/plain": [
       "<class 'statsmodels.iolib.summary.Summary'>\n",
       "\"\"\"\n",
       "                            OLS Regression Results                            \n",
       "==============================================================================\n",
       "Dep. Variable:                   道恩股份   R-squared:                       0.423\n",
       "Model:                            OLS   Adj. R-squared:                  0.415\n",
       "Method:                 Least Squares   F-statistic:                     52.77\n",
       "Date:                Fri, 01 Apr 2022   Prob (F-statistic):           1.25e-25\n",
       "Time:                        10:17:03   Log-Likelihood:                 479.10\n",
       "No. Observations:                 220   AIC:                            -950.2\n",
       "Df Residuals:                     216   BIC:                            -936.6\n",
       "Df Model:                           3                                         \n",
       "Covariance Type:            nonrobust                                         \n",
       "================================================================================\n",
       "                   coef    std err          t      P>|t|      [0.025      0.975]\n",
       "--------------------------------------------------------------------------------\n",
       "const            0.0014      0.002      0.744      0.458      -0.002       0.005\n",
       "RiskPremium1     1.6093      0.217      7.400      0.000       1.181       2.038\n",
       "SMB1             0.0712      0.228      0.312      0.755      -0.378       0.521\n",
       "HML1            -1.8387      0.258     -7.134      0.000      -2.347      -1.331\n",
       "==============================================================================\n",
       "Omnibus:                        9.000   Durbin-Watson:                   2.101\n",
       "Prob(Omnibus):                  0.011   Jarque-Bera (JB):                8.921\n",
       "Skew:                           0.454   Prob(JB):                       0.0116\n",
       "Kurtosis:                       3.385   Cond. No.                         150.\n",
       "==============================================================================\n",
       "\n",
       "Warnings:\n",
       "[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n",
       "\"\"\""
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#去得到每一支股票的beta值\n",
    "x=result[['RiskPremium1','SMB1','HML1']]\n",
    "y=result['道恩股份']\n",
    "X=sm.add_constant(x)#在x的矩阵上加一列“1” 作为常数项回归系数\n",
    "model = sm.OLS(y,X)\n",
    "results = model.fit()\n",
    "#alpha,beta=results.params\n",
    "results.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Exercise: \n",
    "1. Using Fama-French model to test the stocks in stocks50.csv, find the stocks with 5 higheset alpha;\n",
    "2. Expain your model economically,"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Fama-Macbeth Regression"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "FM method to jointly estimate the market price of factor risk A and the amount of factor risk exposure $\\beta$\n",
    "$$R=r_f+\\sum_i \\beta_i\\lambda_i+e_i$$\n",
    "Stage I: time-series to find risk exposure $\\hat{\\beta}_i$\n",
    "\n",
    "Stage II: panel-regression to find risk premium $\\hat{\\lambda}_i$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "matrix([[-0.03575433,  0.0512742 , -0.01073055, ..., -0.04666046,\n",
       "         -0.05147299, -0.01272949],\n",
       "        [ 0.03970956, -0.02147256,  0.04382416, ...,  0.00641766,\n",
       "          0.07280112,  0.01164174],\n",
       "        [ 0.03565849,  0.03221083, -0.05229252, ...,  0.00385453,\n",
       "          0.03140457, -0.007401  ],\n",
       "        ...,\n",
       "        [-0.03512493,  0.02286482,  0.06597226, ..., -0.00320126,\n",
       "         -0.01437528, -0.00603217],\n",
       "        [ 0.00192272,  0.00046097,  0.01059579, ..., -0.00732004,\n",
       "         -0.000327  , -0.00667623],\n",
       "        [ 0.0468015 , -0.00298328, -0.0405158 , ...,  0.00694229,\n",
       "         -0.00133275,  0.02633453]])"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Split using both named colums and ix for larger blocks\n",
    "#dates = result['date'].values\n",
    "factors = result[[ 'SMB1', 'HML1']].values\n",
    "riskfree =result['RiskPremium1'].values\n",
    "portfolios = result.iloc[:, 7:16].values #选取“中国重汽”至“比亚迪”共9支股票\n",
    "\n",
    "# Use mat for easier linear algebra 化为矩阵\n",
    "factors = np.mat(factors)\n",
    "riskfree = np.mat(riskfree)\n",
    "portfolios = np.mat(portfolios)\n",
    "\n",
    "# Shape information\n",
    "T,K = factors.shape\n",
    "T,N = portfolios.shape\n",
    "# Reshape rf and compute excess returns\n",
    "riskfree.shape = T,1\n",
    "excessReturns = portfolios - riskfree\n",
    "excessReturns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['中国重汽', '道恩股份', '白云机场', '东风汽车', '中石化', '中海油', '中石油', '上汽', '比亚迪']"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result.columns[7:16].values\n",
    "columnsname=list(result.columns[7:16].values)\n",
    "columnsname"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 不加rolling的回归"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-1.89492143e-03, -5.37367839e-05])"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Time series regressions\n",
    "X = sm.add_constant(factors)\n",
    "ts_res = sm.OLS(excessReturns, X).fit()\n",
    "alpha = ts_res.params[0]\n",
    "beta = ts_res.params[1:]\n",
    "avgExcessReturns = np.mean(excessReturns, 0)\n",
    "# Cross-section regression\n",
    "cs_res = sm.OLS(avgExcessReturns.T, beta.T).fit()\n",
    "riskPremia = cs_res.params\n",
    "riskPremia"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 时间序列rolling回归"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>中国重汽</th>\n",
       "      <th>道恩股份</th>\n",
       "      <th>白云机场</th>\n",
       "      <th>东风汽车</th>\n",
       "      <th>中石化</th>\n",
       "      <th>中海油</th>\n",
       "      <th>中石油</th>\n",
       "      <th>上汽</th>\n",
       "      <th>比亚迪</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1.773632</td>\n",
       "      <td>-1.939679</td>\n",
       "      <td>1.154557</td>\n",
       "      <td>1.206614</td>\n",
       "      <td>-0.337671</td>\n",
       "      <td>1.468316</td>\n",
       "      <td>1.864572</td>\n",
       "      <td>3.178324</td>\n",
       "      <td>1.088522</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.451112</td>\n",
       "      <td>-2.342475</td>\n",
       "      <td>1.484347</td>\n",
       "      <td>2.270335</td>\n",
       "      <td>-1.378156</td>\n",
       "      <td>1.655851</td>\n",
       "      <td>0.947688</td>\n",
       "      <td>2.174304</td>\n",
       "      <td>1.153209</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.493075</td>\n",
       "      <td>-2.065015</td>\n",
       "      <td>1.076860</td>\n",
       "      <td>2.538182</td>\n",
       "      <td>-1.252490</td>\n",
       "      <td>1.589788</td>\n",
       "      <td>0.905672</td>\n",
       "      <td>1.888344</td>\n",
       "      <td>1.099510</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.320965</td>\n",
       "      <td>-2.106111</td>\n",
       "      <td>1.107963</td>\n",
       "      <td>2.828004</td>\n",
       "      <td>-1.009273</td>\n",
       "      <td>1.631597</td>\n",
       "      <td>0.785865</td>\n",
       "      <td>2.012328</td>\n",
       "      <td>1.134565</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>-1.062272</td>\n",
       "      <td>-2.815817</td>\n",
       "      <td>0.441718</td>\n",
       "      <td>2.476308</td>\n",
       "      <td>-1.745449</td>\n",
       "      <td>1.311758</td>\n",
       "      <td>-0.247780</td>\n",
       "      <td>1.899306</td>\n",
       "      <td>0.996145</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>197</th>\n",
       "      <td>0.827683</td>\n",
       "      <td>-3.496385</td>\n",
       "      <td>0.973290</td>\n",
       "      <td>0.061603</td>\n",
       "      <td>-0.712671</td>\n",
       "      <td>0.382387</td>\n",
       "      <td>-2.029166</td>\n",
       "      <td>0.362082</td>\n",
       "      <td>0.526582</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>198</th>\n",
       "      <td>0.880528</td>\n",
       "      <td>-3.666158</td>\n",
       "      <td>0.896049</td>\n",
       "      <td>0.604581</td>\n",
       "      <td>-0.996168</td>\n",
       "      <td>0.513714</td>\n",
       "      <td>-2.004540</td>\n",
       "      <td>0.655233</td>\n",
       "      <td>0.638718</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>199</th>\n",
       "      <td>1.315477</td>\n",
       "      <td>-3.646204</td>\n",
       "      <td>0.273987</td>\n",
       "      <td>1.186450</td>\n",
       "      <td>-0.846016</td>\n",
       "      <td>0.616147</td>\n",
       "      <td>-1.863748</td>\n",
       "      <td>0.471071</td>\n",
       "      <td>0.766041</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>200</th>\n",
       "      <td>1.447103</td>\n",
       "      <td>-3.392745</td>\n",
       "      <td>0.152811</td>\n",
       "      <td>1.581887</td>\n",
       "      <td>-1.385820</td>\n",
       "      <td>0.702766</td>\n",
       "      <td>-1.752794</td>\n",
       "      <td>1.250000</td>\n",
       "      <td>0.949469</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>201</th>\n",
       "      <td>1.766521</td>\n",
       "      <td>-2.600374</td>\n",
       "      <td>-1.289701</td>\n",
       "      <td>1.885388</td>\n",
       "      <td>-1.209120</td>\n",
       "      <td>0.961208</td>\n",
       "      <td>-1.381299</td>\n",
       "      <td>1.083956</td>\n",
       "      <td>1.592820</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>201 rows × 9 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "         中国重汽      道恩股份      白云机场      东风汽车       中石化       中海油       中石油  \\\n",
       "1    1.773632 -1.939679  1.154557  1.206614 -0.337671  1.468316  1.864572   \n",
       "2    0.451112 -2.342475  1.484347  2.270335 -1.378156  1.655851  0.947688   \n",
       "3    0.493075 -2.065015  1.076860  2.538182 -1.252490  1.589788  0.905672   \n",
       "4    0.320965 -2.106111  1.107963  2.828004 -1.009273  1.631597  0.785865   \n",
       "5   -1.062272 -2.815817  0.441718  2.476308 -1.745449  1.311758 -0.247780   \n",
       "..        ...       ...       ...       ...       ...       ...       ...   \n",
       "197  0.827683 -3.496385  0.973290  0.061603 -0.712671  0.382387 -2.029166   \n",
       "198  0.880528 -3.666158  0.896049  0.604581 -0.996168  0.513714 -2.004540   \n",
       "199  1.315477 -3.646204  0.273987  1.186450 -0.846016  0.616147 -1.863748   \n",
       "200  1.447103 -3.392745  0.152811  1.581887 -1.385820  0.702766 -1.752794   \n",
       "201  1.766521 -2.600374 -1.289701  1.885388 -1.209120  0.961208 -1.381299   \n",
       "\n",
       "           上汽       比亚迪  \n",
       "1    3.178324  1.088522  \n",
       "2    2.174304  1.153209  \n",
       "3    1.888344  1.099510  \n",
       "4    2.012328  1.134565  \n",
       "5    1.899306  0.996145  \n",
       "..        ...       ...  \n",
       "197  0.362082  0.526582  \n",
       "198  0.655233  0.638718  \n",
       "199  0.471071  0.766041  \n",
       "200  1.250000  0.949469  \n",
       "201  1.083956  1.592820  \n",
       "\n",
       "[201 rows x 9 columns]"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#ROLLING REGRESSIONS\n",
    "##time series regressions\n",
    "X = sm.add_constant(factors)#回归的自变量矩阵\n",
    "#创建2个220*9的数据框\n",
    "beta1 = np.arange(220*9).reshape(220,9)  \n",
    "beta1 = pd.DataFrame(beta1)\n",
    "beta2 = np.arange(220*9).reshape(220,9)  \n",
    "beta2 = pd.DataFrame(beta2)\n",
    "#做beta 关于 excessreturn 的滚动回归\n",
    "for i in range(9):\n",
    "    rolstime1 = RollingOLS(excessReturns[:,i], X, window=20)\n",
    "    rres = rolstime1.fit()\n",
    "    beta1[i]=DataFrame(rres.params.copy())[1]\n",
    "    beta2[i]=DataFrame(rres.params.copy())[2]\n",
    "beta1=beta1.iloc[19:,:]\n",
    "beta1.index = np.arange(1, beta1.shape[0] + 1)\n",
    "beta1.columns=[columnsname]\n",
    "beta2=beta2.iloc[19:,:]\n",
    "beta2.index = np.arange(1, beta2.shape[0] + 1)\n",
    "beta2.columns=[columnsname]\n",
    "beta2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 用201组[beta1,beta2]对excessreturn做回归"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>中国重汽</th>\n",
       "      <th>道恩股份</th>\n",
       "      <th>白云机场</th>\n",
       "      <th>东风汽车</th>\n",
       "      <th>中石化</th>\n",
       "      <th>中海油</th>\n",
       "      <th>中石油</th>\n",
       "      <th>上汽</th>\n",
       "      <th>比亚迪</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.010783</td>\n",
       "      <td>0.008948</td>\n",
       "      <td>-0.001327</td>\n",
       "      <td>-0.005730</td>\n",
       "      <td>-0.016259</td>\n",
       "      <td>-0.000923</td>\n",
       "      <td>-0.004058</td>\n",
       "      <td>0.007035</td>\n",
       "      <td>-0.001251</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.015814</td>\n",
       "      <td>0.009847</td>\n",
       "      <td>-0.002208</td>\n",
       "      <td>-0.009627</td>\n",
       "      <td>-0.012420</td>\n",
       "      <td>-0.000956</td>\n",
       "      <td>-0.000083</td>\n",
       "      <td>0.011222</td>\n",
       "      <td>-0.001039</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.016984</td>\n",
       "      <td>0.010354</td>\n",
       "      <td>-0.005800</td>\n",
       "      <td>-0.006595</td>\n",
       "      <td>-0.011201</td>\n",
       "      <td>-0.001153</td>\n",
       "      <td>-0.001238</td>\n",
       "      <td>0.008451</td>\n",
       "      <td>-0.001339</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.014710</td>\n",
       "      <td>0.008464</td>\n",
       "      <td>-0.004309</td>\n",
       "      <td>-0.002248</td>\n",
       "      <td>-0.008824</td>\n",
       "      <td>-0.000340</td>\n",
       "      <td>-0.002236</td>\n",
       "      <td>0.008856</td>\n",
       "      <td>-0.000656</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>0.009651</td>\n",
       "      <td>0.005734</td>\n",
       "      <td>-0.006904</td>\n",
       "      <td>-0.003468</td>\n",
       "      <td>-0.012117</td>\n",
       "      <td>-0.001602</td>\n",
       "      <td>-0.007245</td>\n",
       "      <td>0.009006</td>\n",
       "      <td>-0.001166</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>197</th>\n",
       "      <td>0.002561</td>\n",
       "      <td>-0.002528</td>\n",
       "      <td>0.003673</td>\n",
       "      <td>0.000946</td>\n",
       "      <td>-0.001168</td>\n",
       "      <td>-0.001843</td>\n",
       "      <td>0.000901</td>\n",
       "      <td>-0.002496</td>\n",
       "      <td>-0.006507</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>198</th>\n",
       "      <td>0.001795</td>\n",
       "      <td>-0.002518</td>\n",
       "      <td>0.005026</td>\n",
       "      <td>-0.000700</td>\n",
       "      <td>0.003063</td>\n",
       "      <td>-0.002195</td>\n",
       "      <td>-0.000573</td>\n",
       "      <td>-0.004225</td>\n",
       "      <td>-0.007214</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>199</th>\n",
       "      <td>0.000485</td>\n",
       "      <td>0.000172</td>\n",
       "      <td>0.007167</td>\n",
       "      <td>-0.003707</td>\n",
       "      <td>0.001450</td>\n",
       "      <td>-0.002166</td>\n",
       "      <td>0.000066</td>\n",
       "      <td>-0.006077</td>\n",
       "      <td>-0.006566</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>200</th>\n",
       "      <td>0.001437</td>\n",
       "      <td>-0.002347</td>\n",
       "      <td>0.007929</td>\n",
       "      <td>-0.004944</td>\n",
       "      <td>0.001841</td>\n",
       "      <td>-0.002206</td>\n",
       "      <td>-0.001535</td>\n",
       "      <td>-0.006772</td>\n",
       "      <td>-0.006480</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>201</th>\n",
       "      <td>0.002159</td>\n",
       "      <td>-0.000807</td>\n",
       "      <td>0.003662</td>\n",
       "      <td>-0.003633</td>\n",
       "      <td>0.002179</td>\n",
       "      <td>-0.001428</td>\n",
       "      <td>-0.001187</td>\n",
       "      <td>-0.006912</td>\n",
       "      <td>-0.004375</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>201 rows × 9 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "         中国重汽      道恩股份      白云机场      东风汽车       中石化       中海油       中石油  \\\n",
       "1    0.010783  0.008948 -0.001327 -0.005730 -0.016259 -0.000923 -0.004058   \n",
       "2    0.015814  0.009847 -0.002208 -0.009627 -0.012420 -0.000956 -0.000083   \n",
       "3    0.016984  0.010354 -0.005800 -0.006595 -0.011201 -0.001153 -0.001238   \n",
       "4    0.014710  0.008464 -0.004309 -0.002248 -0.008824 -0.000340 -0.002236   \n",
       "5    0.009651  0.005734 -0.006904 -0.003468 -0.012117 -0.001602 -0.007245   \n",
       "..        ...       ...       ...       ...       ...       ...       ...   \n",
       "197  0.002561 -0.002528  0.003673  0.000946 -0.001168 -0.001843  0.000901   \n",
       "198  0.001795 -0.002518  0.005026 -0.000700  0.003063 -0.002195 -0.000573   \n",
       "199  0.000485  0.000172  0.007167 -0.003707  0.001450 -0.002166  0.000066   \n",
       "200  0.001437 -0.002347  0.007929 -0.004944  0.001841 -0.002206 -0.001535   \n",
       "201  0.002159 -0.000807  0.003662 -0.003633  0.002179 -0.001428 -0.001187   \n",
       "\n",
       "           上汽       比亚迪  \n",
       "1    0.007035 -0.001251  \n",
       "2    0.011222 -0.001039  \n",
       "3    0.008451 -0.001339  \n",
       "4    0.008856 -0.000656  \n",
       "5    0.009006 -0.001166  \n",
       "..        ...       ...  \n",
       "197 -0.002496 -0.006507  \n",
       "198 -0.004225 -0.007214  \n",
       "199 -0.006077 -0.006566  \n",
       "200 -0.006772 -0.006480  \n",
       "201 -0.006912 -0.004375  \n",
       "\n",
       "[201 rows x 9 columns]"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#首先先求出201组的excessreturn\n",
    "excessreturn = np.arange(201*9).reshape(201,9) #创建数据框\n",
    "excessreturn = pd.DataFrame(excessreturn)\n",
    "excessreturn.index = np.arange(1, excessreturn.shape[0] + 1)\n",
    "excessreturn.columns=[columnsname]\n",
    "for i in range(201):\n",
    "    for j in range(9):\n",
    "        excessreturn.iloc[i,j]=np.mean(excessReturns[i:i+20,j])\n",
    "excessreturn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Average</th>\n",
       "      <th>1</th>\n",
       "      <th>2</th>\n",
       "      <th>3</th>\n",
       "      <th>4</th>\n",
       "      <th>5</th>\n",
       "      <th>6</th>\n",
       "      <th>7</th>\n",
       "      <th>8</th>\n",
       "      <th>9</th>\n",
       "      <th>...</th>\n",
       "      <th>192</th>\n",
       "      <th>193</th>\n",
       "      <th>194</th>\n",
       "      <th>195</th>\n",
       "      <th>196</th>\n",
       "      <th>197</th>\n",
       "      <th>198</th>\n",
       "      <th>199</th>\n",
       "      <th>200</th>\n",
       "      <th>201</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Lambda1</th>\n",
       "      <td>-0.001099</td>\n",
       "      <td>-0.009466</td>\n",
       "      <td>-0.010695</td>\n",
       "      <td>-0.010222</td>\n",
       "      <td>-0.006996</td>\n",
       "      <td>-0.007047</td>\n",
       "      <td>-0.007447</td>\n",
       "      <td>-0.007589</td>\n",
       "      <td>-0.005568</td>\n",
       "      <td>-0.003174</td>\n",
       "      <td>...</td>\n",
       "      <td>-0.002111</td>\n",
       "      <td>-0.000702</td>\n",
       "      <td>-0.001572</td>\n",
       "      <td>-0.001063</td>\n",
       "      <td>-0.001491</td>\n",
       "      <td>0.001563</td>\n",
       "      <td>0.002857</td>\n",
       "      <td>0.001668</td>\n",
       "      <td>0.001647</td>\n",
       "      <td>0.000927</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Lambda2</th>\n",
       "      <td>0.000130</td>\n",
       "      <td>-0.002055</td>\n",
       "      <td>-0.001832</td>\n",
       "      <td>-0.001569</td>\n",
       "      <td>-0.001550</td>\n",
       "      <td>-0.001291</td>\n",
       "      <td>-0.001535</td>\n",
       "      <td>-0.001627</td>\n",
       "      <td>-0.002306</td>\n",
       "      <td>-0.001369</td>\n",
       "      <td>...</td>\n",
       "      <td>-0.001381</td>\n",
       "      <td>-0.000987</td>\n",
       "      <td>-0.000605</td>\n",
       "      <td>-0.000611</td>\n",
       "      <td>0.000279</td>\n",
       "      <td>-0.000066</td>\n",
       "      <td>-0.000530</td>\n",
       "      <td>-0.001033</td>\n",
       "      <td>-0.000905</td>\n",
       "      <td>-0.001176</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>2 rows × 202 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "          Average         1         2         3         4         5         6  \\\n",
       "Lambda1 -0.001099 -0.009466 -0.010695 -0.010222 -0.006996 -0.007047 -0.007447   \n",
       "Lambda2  0.000130 -0.002055 -0.001832 -0.001569 -0.001550 -0.001291 -0.001535   \n",
       "\n",
       "                7         8         9  ...       192       193       194  \\\n",
       "Lambda1 -0.007589 -0.005568 -0.003174  ... -0.002111 -0.000702 -0.001572   \n",
       "Lambda2 -0.001627 -0.002306 -0.001369  ... -0.001381 -0.000987 -0.000605   \n",
       "\n",
       "              195       196       197       198       199       200       201  \n",
       "Lambda1 -0.001063 -0.001491  0.001563  0.002857  0.001668  0.001647  0.000927  \n",
       "Lambda2 -0.000611  0.000279 -0.000066 -0.000530 -0.001033 -0.000905 -0.001176  \n",
       "\n",
       "[2 rows x 202 columns]"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#进行201次0LS回归得到201组lambda\n",
    "lambdalist = np.arange(1*2).reshape(2,1)  \n",
    "lambdalist = pd.DataFrame(lambdalist)\n",
    "for i in range(201):\n",
    "    b1=beta1.iloc[i,:].values\n",
    "    b2=beta2.iloc[i,:].values\n",
    "    b1=np.mat(b1)\n",
    "    b2=np.mat(b2)\n",
    "    b=np.append(b1,b2,axis=0)\n",
    "    #B = sm.add_constant(b.T)#将每一组的beta1与beta2分别合并，并加上一列1\n",
    "    excessreturn1=excessreturn.iloc[i,:].values\n",
    "    excessreturn1=np.mat(excessreturn1)\n",
    "    cs_res = sm.OLS(excessreturn1.T,b.T).fit()\n",
    "    lambda1=DataFrame(cs_res.params.copy().T)\n",
    "    lambdalist=pd.concat([lambdalist,lambda1],axis=1)\n",
    "lambdalist\n",
    "Lambda=lambdalist.iloc[:,1:]\n",
    "#Lambda.index=['Lambda0','Lambda1','Lambda2']\n",
    "Lambda.index=['Lambda1','Lambda2']\n",
    "Lambda.columns = np.arange(1, 202)\n",
    "#求均值\n",
    "#L1=np.mean(Lambda.iloc[0,:])\n",
    "L2=np.mean(Lambda.iloc[0,:])\n",
    "L3=np.mean(Lambda.iloc[1,:])\n",
    "Lambda_average= np.arange(2*1).reshape(2,1)  \n",
    "#Lambda_average=DataFrame([L1,L2,L3])\n",
    "Lambda_average=DataFrame([L2,L3])\n",
    "#Lambda_average.index=['Lambda0','Lambda1','Lambda2']\n",
    "Lambda_average.index=['Lambda1','Lambda2']\n",
    "Lambda_average=pd.concat([Lambda_average,Lambda],axis=1)\n",
    "Lambda_average.rename(columns={0:'Average'}, inplace = True)\n",
    "Lambda_average"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Questions: \n",
    "Please finish the rolling regression of the Fama-French 3 factors model (rolling window=60 days);\n",
    "References:https://www.statsmodels.org/stable/examples/notebooks/generated/rolling_ls.html"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
